package scatter.identification.rest.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import scatter.common.ErrorCode;
import scatter.common.LoginUser;
import scatter.common.rest.controller.BaseQueryFormController;
import scatter.common.rest.exception.BusinessBadRequestException;
import scatter.identification.pojo.form.IdentificationApplyForm;
import scatter.identification.pojo.form.IdentificationAuditForm;
import scatter.identification.pojo.form.IdentificationPageQueryForm;
import scatter.identification.pojo.param.IdentificationApplyParam;
import scatter.identification.pojo.po.Identification;
import scatter.identification.pojo.vo.IdentificationVo;
import scatter.identification.rest.IdentificationConfiguration;
import scatter.identification.rest.mapstruct.IdentificationMapStruct;
import scatter.identification.rest.service.IIdentificationService;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * <p>
 * 认证表 前端控制器
 * </p>
 *
 * @author yw
 * @since 2021-11-05
 */
@Api(tags = "认证相关接口")
@RestController
@RequestMapping(IdentificationConfiguration.CONTROLLER_BASE_PATH + "/identification")
public class IdentificationController extends BaseQueryFormController<Identification, IdentificationVo, IdentificationPageQueryForm> {
    @Autowired
    private IIdentificationService iIdentificationService;

    @ApiOperation("根据ID查询认证")
    @PreAuthorize("hasAuthority('Identification:queryById')")
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public IdentificationVo queryById(@PathVariable String id) {
        return super.queryById(id);
    }

    @ApiOperation("根据ID删除认证")
    @PreAuthorize("hasAuthority('Identification:deleteById')")
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Override
    public boolean deleteById(@PathVariable String id) {
        return super.deleteById(id);
    }

    @ApiOperation("不分页查询认证")
    @PreAuthorize("hasAuthority('Identification:getList')")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public List<IdentificationVo> getList(IdentificationPageQueryForm listPageForm) {
         return super.getList(listPageForm);
    }

    @ApiOperation("分页查询认证")
    @PreAuthorize("hasAuthority('Identification:getPage')")
    @GetMapping("/getPage")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public IPage<IdentificationVo> getPage(IdentificationPageQueryForm listPageForm) {
         return super.getPage(listPageForm);
    }


    @ApiOperation("认证审核")
    @PreAuthorize("hasAuthority('Identification:audit')")
    @PostMapping("/audit")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean audit(@RequestBody @Valid IdentificationAuditForm auditForm) {
        return iIdentificationService.audit(auditForm.getId(),auditForm.getIsAudited(),auditForm.getAuditFailReason());
    }

    @ApiOperation("申请认证")
    @PreAuthorize("hasAuthority('user')")
    @PostMapping("/apply")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean apply(@RequestBody @Valid IdentificationApplyForm applyForm, @ApiIgnore LoginUser loginUser) {

        if (isStrEmpty(applyForm.getContent()) && (applyForm.getContentMap() == null || applyForm.getContentMap().isEmpty())) {
            throw new BusinessBadRequestException("申请内容不能为空");
        }
        if (isStrEmpty(applyForm.getContent())) {
            applyForm.setContent(toJsonStr(applyForm.getContentMap()));
        }
        IdentificationApplyParam identificationApplyParam = IdentificationMapStruct.INSTANCE.applyFormToParam(applyForm);
        identificationApplyParam.setUserId(loginUser.getId());
        return iIdentificationService.apply(identificationApplyParam);
    }

    @ApiOperation("查询我是否认证")
    @PreAuthorize("hasAuthority('user')")
    @GetMapping("/hasIdentified/{code}")
    @ResponseStatus(HttpStatus.OK)
    public Boolean hasIdentified(@PathVariable String code,@ApiIgnore LoginUser loginUser) {
        boolean b = iIdentificationService.hasIdentified(code, loginUser.getId());
        if (!b) {
            throw new BusinessBadRequestException("尚未认证", ErrorCode.ERROR_NO_IDENTIFICATION.getCode());
        }
        return b;
    }
    @ApiOperation("查询我的认证信息")
    @PreAuthorize("hasAuthority('user')")
    @GetMapping("/getByCode/{code}")
    @ResponseStatus(HttpStatus.OK)
    public IdentificationVo getByCode(@PathVariable String code,@ApiIgnore LoginUser loginUser) {
        Identification byCodeAndUserId = iIdentificationService.getByCodeAndUserId(code, loginUser.getId());
        if (byCodeAndUserId == null) {
            throw new BusinessBadRequestException("尚未认证", ErrorCode.ERROR_NO_IDENTIFICATION.getCode());
        }
        return getVo(byCodeAndUserId);
    }
    @ApiOperation("查询我是否认证，多个")
    @PreAuthorize("hasAuthority('user')")
    @GetMapping("/hasIdentifieds/{codes}")
    @ResponseStatus(HttpStatus.OK)
    @ApiResponse(code = 200, message = "返回每一个code对应的boolean值")
    public Map<String,Boolean> hasIdentifieds(@PathVariable String codes, @ApiIgnore LoginUser loginUser) {
        return iIdentificationService.hasIdentified(newArrayList(codes.split(",")), loginUser.getId());
    }
    @ApiOperation("查询我是否认证信息")
    @PreAuthorize("hasAuthority('user')")
    @GetMapping("/getByCodes/{codes}")
    @ResponseStatus(HttpStatus.OK)
    @ApiResponse(code = 200, message = "返回每一个code对应的boolean值")
    public Map<String,IdentificationVo> getByCodes(@PathVariable String codes, @ApiIgnore LoginUser loginUser) {
        Map<String, Identification> byCodes = iIdentificationService.getByCodes(newArrayList(codes.split(",")), loginUser.getId());
        Map<String, IdentificationVo> result = new HashMap<>(byCodes.size());
        Identification identificationTemp = null;
        for (String code : byCodes.keySet()) {
            identificationTemp = byCodes.get(code);
            result.put(code,getVo(identificationTemp));
        }
        return result;
    }
}
